<?php
namespace App\Services;


use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;

class SmsService {

    public static $errorMessage = "";

    public static function sendSms($phone, $code) {

        $config = new Config([
            "accessKeyId" => env("ALIYUN_ACCESS_KEY_ID"),
            "accessKeySecret" => env("ALIYUN_ACCESS_KEY_SECRET")
        ]);

        $config->endpoint = "dysmsapi.aliyuncs.com";

        $client =  new Dysmsapi($config);

        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers"  => $phone,
            "signName"      => env('ALIYUN_SMS_SIGN_NAME'),
            "templateCode"  => env('ALIYUN_SMS_TEMPLATE_CODE'),
            "templateParam" => json_encode(['code' => $code])
        ]);

        try {
            $res = $client->sendSms($sendSmsRequest) -> toArray();

            if($res['body']['Code'] != 'OK') {
                throw new \Exception($res['body']['Message']);
            }

            return true;
        } catch (\Exception $exception) {
            self::$errorMessage = $exception->getMessage();

            return false;
        }
    }
}
